//
//  RadioSecondViewController.m
//  A_program
//
//  Created by BayMax on 15/5/23.
//  Copyright (c) 2015年 BayMax. All rights reserved.
//

#import "RadioSecondViewController.h"
#import "RadioModel.h"
#import "RadioTableViewCell.h"
#import "RadioThirdViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "SecondListModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MJRefresh.h"
#import <Reachability.h>
#import "RadioThirdButton.h"
#import "ConnectModel.h"
#import "NovelDatabase.h"
#import "NovelModel.h"
#import "LoginNextViewController.h"


@interface RadioSecondViewController ()<UITableViewDataSource, UITableViewDelegate,RadioThirdButtonDelegate>

@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic,retain)NSString *detailsPath;
@property (nonatomic,assign) NSInteger detailsPageCount;
@property (nonatomic, retain) UISegmentedControl *segmen;

@end

@implementation RadioSecondViewController

- (void)dealloc
{
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.detailsPageCount = 2;
        self.segmen = [[UISegmentedControl alloc]init];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    [self createView];
    [self createWeb];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
}
//判断网络使用
-(BOOL) isConnectionAvailable:(NSInteger)count{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            NSLog(@"没网");
            if (count == 1) {
                [self.tableView.header endRefreshing];
            }else if(count == 2){
                [self.tableView.footer endRefreshing];
            }
            
            [self alertView:@"没有网络连接"];
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            NSLog(@"用的WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            NSLog(@"3G");
            [self alertView:@"使用3G连接"];
            break;
    }
    
    
    return isExistenceNetwork;
}
// 警告框
- (void)alertView:(NSString *)str
{
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
    [alert setDelegate:self];
    [alert show];
    [alert release];
    
}
#pragma mark -
#pragma mark 网络请求
- (void)createWeb
{
    if ([self isConnectionAvailable:0]) {
        NSString *str = self.secondTname;
        NSString *urlPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=radio&condition=hot&device=iPhone&page=1&per_page=20&status=0&tag_name=%@", str];
        
        //将网址里面的汉字转换成字符串
        urlPath = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager GET:urlPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSData *data = operation.responseData;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //        NSLog(@"json is %@", dict);
            NSArray *array = [dict objectForKey:@"list"];
            NSMutableArray *smallArray = [NSMutableArray array];
            for (NSMutableDictionary *dic in array) {
                SecondListModel *model = [[SecondListModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [smallArray addObject:model];
            }
            self.array = [NSMutableArray arrayWithArray:smallArray];
            [self.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"下载错误 is %@", error);
        }];
  
    }
    
    
}

#pragma mark -
#pragma mark 创建tableView，创建UISegmentedControl
- (void)createView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 35, self.view.frame.size.width, self.view.frame.size.height - 49)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData:)];
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreDate)];
    [self.view addSubview:self.tableView];
    [self.tableView release];
    
    NSMutableArray *array = [NSMutableArray array];
    [array addObject:@"最火"];
    [array addObject:@"最近更新"];
    [array addObject:@"经典"];
    
    self.segmen = [[UISegmentedControl alloc]initWithItems:array];
    self.segmen.frame = CGRectMake(5, 5, self.view.frame.size.width - 10, 30);
    self.segmen.tintColor = [UIColor orangeColor];
    self.segmen.selectedSegmentIndex = 0;
    [self.segmen addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmen];
    [self.segmen release];
}

- (void)loadNewData:(id)sender
{
    if ([self isConnectionAvailable:1]) {
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    }
   
}

- (void)loadMoreDate
{
    if ([self isConnectionAvailable:2]) {
        if (self.segmen.selectedSegmentIndex == 0) {
            
            NSString *str = self.secondTname;
            NSString *urlPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=radio&condition=hot&device=iPhone&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount, str];
            
            urlPath = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager GET:urlPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSData *data = operation.responseData;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                NSArray *array = [dict objectForKey:@"list"];
                //        NSLog(@"array = %@", array);
                
                for (NSMutableDictionary *dic in array) {
                    SecondListModel *model = [[SecondListModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.array addObject:model];
                }
                
                [self.tableView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"下载错误 is %@", error);
            }];
            
            
        }else if(self.segmen.selectedSegmentIndex == 1){
            
            NSString *str = self.secondTname;
            NSString *urlPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=radio&condition=recent&device=iPhone&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount, str];
            
            urlPath = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager GET:urlPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSData *data = operation.responseData;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                //        NSLog(@"json is %@", dict);
                NSArray *array = [dict objectForKey:@"list"];
                //        NSLog(@"array = %@", array);
                
                for(NSMutableDictionary *dic in array) {
                    SecondListModel *model = [[SecondListModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.array addObject:model];
                }
                
                [self.tableView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"下载错误 is %@", error);
            }];
            
        }else if(self.segmen.selectedSegmentIndex == 2){
            
            NSString *str = self.secondTname;
            NSString *urlPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=radio&condition=classic&device=iPhone&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount, str];
            
            urlPath = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager GET:urlPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSData *data = operation.responseData;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                //        NSLog(@"json is %@", dict);
                NSArray *array = [dict objectForKey:@"list"];
                //        NSLog(@"array = %@", array);
                
                for (NSMutableDictionary *dic in array) {
                    SecondListModel *model = [[SecondListModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.array addObject:model];
                }
                
                [self.tableView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"下载错误 is %@", error);
            }];
            
        }
        
        self.detailsPageCount += 1;
        [self.tableView.footer endRefreshing];
    }
   
}

#pragma mark -
#pragma mark Segment点击事件
- (void)segAction:(id)sender
{
    UISegmentedControl *segmen = (UISegmentedControl *)sender;
    switch (segmen.selectedSegmentIndex) {
        case 0:
        {
            self.detailsPageCount = 1;
            [self.array removeAllObjects];
            NSString *str = self.secondTname;
            NSString *urlPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=radio&condition=hot&device=iPhone&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount, str];
            
            urlPath = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager GET:urlPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSData *data = operation.responseData;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                //        NSLog(@"json is %@", dict);
                NSArray *array = [dict objectForKey:@"list"];
                //        NSLog(@"array = %@", array);
                
                for (NSMutableDictionary *dic in array) {
                    SecondListModel *model = [[SecondListModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.array addObject:model];
                }
                
                [self.tableView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"下载错误 is %@", error);
            }];
            
        }
            break;
        case 1:
        {
            self.detailsPageCount = 1;
            [self.array removeAllObjects];
            NSString *str = self.secondTname;
            NSString *urlPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=radio&condition=recent&device=iPhone&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount, str];
            
            urlPath = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager GET:urlPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSData *data = operation.responseData;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                //        NSLog(@"json is %@", dict);
                NSArray *array = [dict objectForKey:@"list"];
                //        NSLog(@"array = %@", array);
                
                for (NSMutableDictionary *dic in array) {
                    SecondListModel *model = [[SecondListModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.array addObject:model];
                }
                
                [self.tableView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"下载错误 is %@", error);
            }];
        }
            break;
        case 2:
        {
            self.detailsPageCount = 1;
            [self.array removeAllObjects];
            NSString *str = self.secondTname;
            NSString *urlPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=radio&condition=classic&device=iPhone&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount, str];
            
            urlPath = [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager GET:urlPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSData *data = operation.responseData;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                //        NSLog(@"json is %@", dict);
                NSArray *array = [dict objectForKey:@"list"];
                //        NSLog(@"array = %@", array);
                
                for (NSMutableDictionary *dic in array) {
                    SecondListModel *model = [[SecondListModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.array addObject:model];
                }
                
                [self.tableView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"下载错误 is %@", error);
            }];
            
        }
            break;
            
        default:
            break;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.array count];
}

#pragma mark -
#pragma mark tableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"cell";
    RadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[RadioTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    }
    
    SecondListModel *model = [self.array objectAtIndex:indexPath.row];
    cell.nameLabel.text = model.title;
    
    NSString *strt = [NSString stringWithFormat:@"%@", model.playsCounts];
    cell.countLabel.text = strt;
    
    [cell.listImageView sd_setImageWithURL:[NSURL URLWithString:model.albumCoverUrl290] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    cell.radioThirdButtonDelegate = self;
    NSString *str1 = [NSString stringWithFormat:@"%@",model.myId];
    [cell cellButton:str1];
    
    
    
    return cell;
    
}
//收藏按钮的点击事件
- (void)createRadioThirdButtonAction:(NSString *)collect{
    
    NSUserDefaults *myLoginName = [[NSUserDefaults alloc]init];
#pragma mark -
#pragma mark 登陆姓名为空就跳到登陆界面
    if ([[myLoginName objectForKey:@"loginName"] length] == 0) {
        
        LoginNextViewController *loginNext = [[LoginNextViewController alloc]init];
        [self.navigationController pushViewController:loginNext animated:YES];
        [loginNext release];
    }else{
        
        NSInteger albumId = [collect integerValue];
        
        NSMutableArray *idArray = (NSMutableArray *)[NovelDatabase selectNameAlbumId:albumId];
        
        //取得所有为空
        if (idArray.count == 0) {
            NSLog(@"所有数组为空");
            //判断登录状态
            if ([[myLoginName objectForKey:@"state"]isEqualToString:@"登录"]) {
                NSString *collectStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15",collect];
                [ConnectModel connectWithUrl:collectStr block:^(NSData *data) {
                    self.novelModel = [[NovelModel alloc]init];
                    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSMutableDictionary *myHeaderDic = [dic objectForKey:@"album"];
                    [self.novelModel setValuesForKeysWithDictionary:myHeaderDic];
                    //读取userDefault的信息
                    self.novelModel.loginName = [myLoginName objectForKey:@"loginName"];
                    self.novelModel.playKind = @"radio";
                    self.novelModel.albumIdMin = [collect integerValue];
                    [NovelDatabase insertWithModel:self.novelModel];
                }];
#pragma mark-
#pragma mark在这里是没有登陆
            }else{
                LoginNextViewController *loginNext = [[LoginNextViewController alloc]init];
                [self.navigationController pushViewController:loginNext animated:YES];
            }
            
#pragma mark -
#pragma mark这里得判断人和id()
        }else{
            //判断所有id号有没有使用
            NSString *myNewAlbumId = [NSString string];
            NSMutableString *countStr = [NSMutableString string];
            NSString *albumIdStr = [NSString string];
            [countStr appendFormat:@"%@",collect];
            for (NovelModel *model in idArray) {
                for (int i = 0; i < 1000; i++) {
                    [countStr appendFormat:@"%d",36];
                    albumIdStr = [NSString stringWithFormat:@"%ld",model.albumId];
                    if (![albumIdStr isEqualToString:countStr]&&![countStr length]==0 ) {
                        //取得没有使用的值
                        myNewAlbumId = [NSString stringWithString:countStr];
                        break;
                    }
                    
                }
                
            }
            
            NSLog(@"这里id数组不为空");
            NSMutableArray *myPersonArray = (NSMutableArray *)[NovelDatabase selectNameAlbumId:albumId loginName:[myLoginName objectForKey:@"loginName"]];
            //数组
            if (myPersonArray.count == 0) {
                if ([[myLoginName objectForKey:@"state"]isEqualToString:@"登录"]) {
                    NSString *collectStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15",collect];
                    [ConnectModel connectWithUrl:collectStr block:^(NSData *data) {
                        self.novelModel = [[NovelModel alloc]init];
                        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                        NSMutableDictionary *myHeaderDic = [dic objectForKey:@"album"];
                        [self.novelModel setValuesForKeysWithDictionary:myHeaderDic];
                        //读取userDefault的信息
                        self.novelModel.loginName = [myLoginName objectForKey:@"loginName"];
                        self.novelModel.playKind = @"radio";
                        //假如没有使用的ID
                        self.novelModel.albumId = [myNewAlbumId integerValue];
                        self.novelModel.albumIdMin = [collect integerValue];
                        [NovelDatabase insertWithModel:self.novelModel];
                    }];
#pragma mark-
#pragma mark在这里是没有登陆
                }else{
                    
                    LoginNextViewController *loginNext = [[LoginNextViewController alloc]init];
                    [self.navigationController pushViewController:loginNext animated:YES];
                }
                
            }else{
                
                NSLog(@"已收藏状态");
                
            }
            
        }
        
        
    }
    

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

#pragma mark -
#pragma mark 跳转页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RadioThirdViewController *third = [[RadioThirdViewController alloc]init];
    SecondListModel *model = [self.array objectAtIndex:indexPath.row];
    third.model = model;
    third.myId = model.myId;
    [self.navigationController pushViewController:third animated:YES];
    [third release];

}


@end
